1   /*
2    * Copyright (C) 2007 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.google.common.io;
18  
19  import com.google.common.annotations.Beta;
20  
21  import java.io.FilterInputStream;
22  import java.io.IOException;
23  import java.io.InputStream;
24  
25  import javax.annotation.Nullable;
26  
27  /**
28   * An {@link InputStream} that counts the number of bytes read.
29   *
30   * @author Chris Nokleberg
31   * @since 1.0
32   */
33  @Beta
34  public final class CountingInputStream extends FilterInputStream {
35  
36    private long count;
37    private long mark = -1;
38  
39    /**
40     * Wraps another input stream, counting the number of bytes read.
41     *
42     * @param in the input stream to be wrapped
43     */
44    public CountingInputStream(@Nullable InputStream in) {
45      super(in);
46    }
47  
48    /** Returns the number of bytes read. */
49    public long getCount() {
50      return count;
51    }
52  
53    @Override public int read() throws IOException {
54      int result = in.read();
55      if (result != -1) {
56        count++;
57      }
58      return result;
59    }
60  
61    @Override public int read(byte[] b, int off, int len) throws IOException {
62      int result = in.read(b, off, len);
63      if (result != -1) {
64        count += result;
65      }
66      return result;
67    }
68  
69    @Override public long skip(long n) throws IOException {
70      long result = in.skip(n);
71      count += result;
72      return result;
73    }
74  
75    @Override public synchronized void mark(int readlimit) {
76      in.mark(readlimit);
77      mark = count;
78      // it's okay to mark even if mark isn't supported, as reset won't work
79    }
80  
81    @Override public synchronized void reset() throws IOException {
82      if (!in.markSupported()) {
83        throw new IOException("Mark not supported");
84      }
85      if (mark == -1) {
86        throw new IOException("Mark not set");
87      }
88  
89      in.reset();
90      count = mark;
91    }
92  }